No. The statement
str = value ;
is (apparently) asking that the primitive data type contained in value
be placed in the reference variable str
.
This cannot be done.
Here is a further modification of the example program:
class egString3 { public static void main ( String[] args ) { String str; str = new String("The Gingham Dog"); System.out.println(str); str = new String("The Calico Cat"); System.out.println(str); } } |
The program does exactly what you would expect. It writes out:
The Gingham Dog The Calico Cat
Let us look at some of the details involved in doing this.
Statement | Action |
---|---|
str = new String( |
Create the FIRST object.
Put a reference to this object into str |
System.out.println(str); |
Follow the reference in str to the FIRST object. Get the data in it and print it. |
str = new String( |
Create a SECOND object.
Put a reference to the SECOND object into str. At this point, there is no reference to the first object. It is now "garbage." |
System.out.println(str); |
Follow the reference in str to the SECOND object. Get the data in it and print it. |
Notice that:
The word garbage is the correct term for objects that are not referred to by any reference variable. Since they cannot be found (by your program) in effect they do not exist. This situation is common and not usually a mistake. As a program executes, objects are created. Then when they are no longer needed references to them are discarded. However, a part of the Java system called the garbage collector reclaims the lost objects (garbage) so that the memory they are made of can be used again.